<template>
  <div class="app-container" id="app-main">
    <!-- 查询和其他操作 -->
    <div class="filter-container" style="margin: 10px 0 10px 0">
      <div class="filter-container">
        <el-input
          v-model="query.roleName"
          clearable
          class="filter-item-left"
          style="width: 200px"
          size="small"
          :placeholder="$t('message.validate.inputrole')"
          @keyup.enter="handleFind"
        />
        <el-button class="filter-item-right" size="small" icon="el-icon-search" @click="handleFind">
          {{ $t('message.operate.search') }}
        </el-button>
        <el-button
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-refresh"
          @click="handleReset"
        >
          {{ $t('message.operate.reset') }}
        </el-button>
      </div>
      <div class="filter-container2">
        <el-button
          v-limit="'XTGL:YWJS:ADD'"
          class="filter-item"
          size="small"
          type="primary"
          @click="handleAdd"
        >
          {{ $t('message.role.add') }}
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
      :max-height="maxHeight"
    >
      <el-table-column type="expand">
        <template #default="props">
          <el-table :data="props.row.users" border :max-height="150">
            <el-table-column :label="$t('message.role.name')" align="center">
              <template #default="scope">
                <span>{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('message.user.cname')" align="center">
              <template #default="scope">
                <span>{{ scope.row.cname }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('message.user.phone')" align="center">
              <template #default="scope">
                <span>{{ scope.row.phone }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('message.user.email')" align="center">
              <template #default="scope">
                <span>{{ scope.row.email }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.table.index')" width="50" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.name')" width="240" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.code')" width="240" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleCode }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.role.desc')" align="center">
        <template #default="scope">
          <span>{{ scope.row.roleDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.form.createTime')"
        width="200"
        align="center"
        prop="createTime"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.operate.name')" width="200" align="center">
        <template #default="scope">
          <el-button
            v-limit="'XTGL:YWJS:EDIT'"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            {{ $t('message.operate.edit') }}
          </el-button>
          <el-button
            v-limit="'XTGL:YWJS:DELETE'"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            {{ $t('message.operate.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog
      v-if="dialogFormVisible"
      v-model="dialogFormVisible"
      :title="title"
      append-to-body
      :width="dialogWidth"
    >
      <el-form ref="form" :model="form" :rules="dataRule">
        <el-form-item
          :label="$t('message.role.name')"
          :label-width="formLabelWidth"
          prop="roleName"
        >
          <el-input
            v-model="form.roleName"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.role.code')"
          :label-width="formLabelWidth"
          prop="roleCode"
        >
          <el-input
            v-model="form.roleCode"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.user.roleDesc')"
          :label-width="formLabelWidth"
          prop="roleDesc"
        >
          <el-input
            v-model="form.roleDesc"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>
        <!-- 用户 -->
        <el-form-item :label="$t('message.user.name')" :label-width="formLabelWidth" prop="roleId">
          <user-list-modal
            v-model="form.userNames"
            :default-users="defaultUsers"
            :multiple="multiple"
            @update:modelValue="handleUserList"
            @update:users="handleUsers"
            :devType="'platform'"
          />
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">
          {{ $t('message.operate.cancel') }}
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          {{ $t('message.operate.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, addRole, updateRole, deleteRole } from '../api/roles'
import { getUserById } from '../api/org'
import { getMenus } from '../api/menu'
import { parseTime } from '@/utils/index'
import { getDeptTree } from '../api/dept'
// import UserListModal from '../components/UserListModal'
import UserListModal from '@/views/project/components/UserListModal'
import { pick } from 'lodash'
import { mapGetters } from 'vuex'

export default {
  components: {
    UserListModal,
  },
  emits: ['close'],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$i18n.t('message.validate.required')))
      } else if (!/^[_a-zA-Z0-9]+$/.test(value)) {
        callback(new Error('角色编码仅可包含大小写字母、数字、下划线'))
      } else {
        this.$refs.form.validateField('checkPass')
        callback()
      }
    }
    return {
      tableData: [],
      keyword: '',
      title: '',
      dialogFormVisible: false, // 控制弹出框
      defaultUsers: [],
      formLabelWidth: '120px',
      isEditForm: false,
      multiple: true,
      // dateScopes: [
      //   {
      //     id: 1,
      //     des: '全部',
      //   },
      //   {
      //     id: 2,
      //     des: '本级',
      //   },
      //   {
      //     id: 3,
      //     des: '本级以及子级',
      //   },
      //   {
      //     id: 4,
      //     des: '自定义',
      //   },
      // ],
      deptData: [],
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      query: {
        roleName: '',
      },
      form: {
        roleId: 0,
        roleName: '',
        roleCode: '',
        roleDesc: '',
        roleMenus: [],
        dsType: 0,
        deptName: '',
        deptId: 1,
        userIds: [], // 用户
        userNames: [], // 用户姓名
      },
      // 分类菜单列表
      menuData: [],
      // tree配置项
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      selectRole: {},
      checkAll: false,
      menuIds: [],
      // 表单校验
      dataRule: {
        roleName: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        roleCode: [{ required: true, trigger: 'change', validator: validatePass }],
      },
      loading: false,
      deptIds: [],
      height: 0,
    }
  },
  computed: {
    // ...mapGetters(['ismobile']),
    maxHeight() {
      return this.height - 158
    },
  },
  mounted() {
    this.height = document.getElementById('app-main').offsetHeight
  },
  created() {
    this.findTreeData()
    this.roleList()
    this.setDialogWidth()
  },
  methods: {
    parseTime,
    // 获取角色
    roleList: function () {
      this.loading = true
      const params = {
        keyword: this.query.roleName,
        roleType: '2',
      }
      getRoles(params).then((response) => {
        this.tableData = response.data.data
        this.loading = false
      })
    },
    // 获取菜单树
    findTreeData: function () {
      this.menuLoading = true
      getMenus().then((res) => {
        this.menuData = res.data.data
        this.menuLoading = false
      })
    },
    setDialogWidth() {
      //  if (this.ismobile){
      //   this.dialogWidth = '90%'
      // } else {
      //   this.dialogWidth = '50%'
      // }
      this.dialogWidth = '50%'
    },
    // 树节点选择监听
    handleMenuCheckChange(data, check) {
      if (check) {
        // 节点选中时同步选中父节点
        const parentId = data.parentId
        this.$refs.menuTree.setChecked(parentId, true, false)
      } else {
        // 节点取消选中时同步取消选中子节点
        if (data.children != null) {
          data.children.forEach((element) => {
            this.$refs.menuTree.setChecked(element.id, false, false)
          })
        }
      }
    },

    handleFind: function () {
      this.roleList()
    },
    handleReset: function () {
      this.query = {
        roleName: '',
      }
      this.roleList()
    },
    opened() {
      if (this.$store.state.app.device == 'mobile') {
        this.$refs.dialog.width = '90%'
      } else {
        this.$refs.dialog.width = '50%'
      }
    },
    // 添加角色
    handleAdd() {
      // console.log(this.form);
      this.dialogFormVisible = true
      this.title = this.$i18n.t('message.role.add')
      this.form = {
        roleId: 0,
        roleName: '',
        roleCode: '',
        roleDesc: '',
        roleMenus: [],
        roleDepts: [],
        // 数据权限类型
        dsType: '',
        deptName: '',
        deptId: 1,
        roleType: '2',
      }
      this.defaultUsers = []
      this.isEditForm = false
    },
    handleUserList (ids,names){
      console.log(this.form,'this.form');
      console.log(ids,names, 'handleUserList')
      this.form.userIds=ids
      this.form.userNames=names
    },
    handleUsers(selectedRows){
      console.log(selectedRows, 'handleUsers')
    },
    // 编辑角色
    handleEdit: function (row) {
      console.log(row,'handleEdit');
      this.dialogFormVisible = true
      this.isEditForm = true
      this.title = this.$i18n.t('message.role.edit')
      this.defaultUsers = row.users || []
      // if (row.roleId != null) {
      //   getUserById(row.roleId).then((res) => {
      //     this.defaultUsers = res.data.data || []
      //     this.orgid = row.roleId
      //   })
      // }

      this.form = row
      this.form.userNames = row.users?.map(item=>item.cname)
      this.form.userIds = row.users?.map(item=>item.userId)
      // this.defaultUsers = this.form.userIds
      this.deptIds = []
    },

    handleDelete: function (row) {
      const that = this
      this.$confirm(this.$i18n.t('message.role.delete'), this.$i18n.t('message.operate.hint'), {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      }).then(() => {
        deleteRole(row.roleId).then((response) => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg,
            })
            that.roleList()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
      })
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = pick(this.form, [
            'roleDesc',
            'roleId',
            'roleCode',
            'roleName',
            'roleType',
            'userIds',
          ])
          if (this.isEditForm) {
            updateRole(params).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.roleList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data,
                })
              }
            })
          } else {
            addRole(params).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.roleList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          }
        }
      })
    },
    // 加载机构列表
    findDeptTree: function () {
      getDeptTree().then((res) => {
        this.deptData = res.data.data
      })
    },
    changeScope() {
      this.deptIds = []
      if (this.form.dsType === 4) {
        this.findDeptTree()
      }
    },
  },
}
</script>
